import { defineStore } from 'pinia'
import listApi from '../api/list'

export const useListStore = defineStore('list', {
    state: () => ({
        lists: [],
        currentListId: null,
        loading: false,
        error: null
    }),
    getters: {
        getLists: (state) => state.lists
    },
    actions: {
        async fetchLists(userId) {
            this.loading = true
            this.error = null
            try {
                this.lists = await listApi.getLists(userId)

                if (this.lists.length > 0 && !this.currentListId) {
                    this.setCurrentList(this.lists[0].id)
                }
            } catch (error) {
                this.error = error.message
                console.error('获取列表失败:', error)
            } finally {
                this.loading = false
            }
        },

        async createList(listData) {
            try {
                const newList = await listApi.createList(listData)
                this.lists.push(newList)
                return newList
            } catch (error) {
                console.error('创建列表失败:', error)
                throw error
            }
        },

        async updateList(id, listData) {
            try {
                await listApi.updateList(id, listData)
                const index = this.lists.findIndex(list => list.id === id)
                if (index !== -1) {
                    this.lists[index] = { ...this.lists[index], ...listData }
                }
            } catch (error) {
                console.error('更新列表失败:', error)
                throw error
            }
        },

        async deleteList(id) {
            try {
                await listApi.deleteList(id)
                this.lists = this.lists.filter(list => list.id !== id)
                if (this.currentListId === id) {
                    this.currentListId = this.lists[0]?.id || null
                }
            } catch (error) {
                console.error('删除列表失败:', error)
                throw error
            }
        },

        setCurrentList(id) {
            this.currentListId = id
        }
    }
})